package cn.oowoo.rabbitmq.delay;

import cn.oowoo.rabbitmq.config.RabbitConfig;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @Author: Zhangbin
 * @Date: 2021/5/9 14:55
 * @Description:  普通生产者，给每条消息增加过期时间
 **/
public class DealyProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitConfig.createConnection();
        // 创建消息通道
        Channel channel = connection.createChannel();

        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder()
                 .deliveryMode(2)
                .contentEncoding("UTF-8")
                .contentType("text/plain");
        Map<String, Object> headers = new HashMap<>();

        for(int i=0;i<10;i++){
            String msg = "测试延迟队列消息.... "+ i +"--->消息发送时间:"+LocalDateTime.now();
            if( i == 0){
                headers.put("x-delay", 20000);
            } else if(i== 1){
                headers.put("x-delay", 15000);
            }else if(i== 2){
                headers.put("x-delay", 10000);;
            }else if(i== 3){
                headers.put("x-delay", 8000);
            }else if(i== 4){
                headers.put("x-delay", 11000);
            }else if(i==5){
                headers.put("x-delay", 10000);
            } else{
                if(headers.containsKey("x-delay"))headers.remove("x-delay");
            }
            /*
                理论上消费顺序应该是 6 7 8 9 3 2 5 4 1 0
             */
            builder.headers(headers);
            AMQP.BasicProperties properties = builder.build();
            channel.basicPublish(RabbitConfig.EXCHANGE_DEALY_NAME,RabbitConfig.ROUTING_DELAY_KEY,properties,msg.getBytes());
        }
        //消息发送完毕关闭信道，关闭链接
        channel.close();
        connection.close();
    }
}
